package com.leesche.zcsp.node.web.controller.template;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import com.leesche.zcsp.node.app.v1.timer.TokenCacheTimer;
import com.leesche.zcsp.node.utils.web.gernerator.TokenGernerator;
import com.leesche.zcsp.node.utils.web.gernerator.UUIDGenerateUtil;
import com.leesche.zcsp.node.web.model.SysUserToken;
import com.leesche.zcsp.node.web.service.SysUserTokenService;
import com.leesche.zcsp.node.web.service.impl.data.read.QuerySysUserCondition;
import com.leesche.zcsp.node.web.service.impl.data.read.QuerySysUserTokenCondition;
import com.leesche.zcsp.node.web.service.impl.data.read.SysUserDto;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.leesche.zcsp.node.pay.wecha.service.WechatService;
import com.leesche.zcsp.node.utils.security.QEncodeUtil;
import com.leesche.zcsp.node.utils.web.SessionManager;
import com.leesche.zcsp.node.utils.web.messge.WebResult;
import com.leesche.zcsp.node.utils.web.validation.Regex;
import com.leesche.zcsp.node.web.constants.Constants;
import com.leesche.zcsp.node.web.model.SysUser;
import com.leesche.zcsp.node.web.service.SysUserService;
import com.leesche.zcsp.node.web.service.privilege.PrivilegeService;
import com.leesche.zcsp.node.web.vo.Account;

/**
 * @author Jerry Chan
 * @version V1.0
 * @Title: node
 * @Package com.leesche.zcsp.node.web.controller.web.user.template
 * @Description:( 在这里描述这个类是做什么的 )
 * @date 2016年10月14日 22:20
 */
public class LoginTemplate extends AccessTemplate {

    @Autowired
    protected WechatService wechatService;

    @Autowired
    protected SysUserService sysUserService;

    @Autowired
    protected PrivilegeService privilegeService;

    @Autowired
    protected SysUserTokenService sysUserTokenService;


    /**
     * @param accout    登录的账户信息
     * @param loginType 登录的类型
     * @return 登录结果
     * @Title: userLogin(Account accout, Integer loginType)
     * @Description: TODO(PC端用户、微信用户登录)
     * @author Jerry
     * @date 2016-10-17 02:57:42
     */
    protected Map<String, Object> userLogin(Account accout, Integer loginType) throws Exception {

        SysUser sysUser = new SysUser();

        /**
         * 验证当前用户使用的是手机还是邮箱或者是用户登录
         */
        if (Regex.isEmail(accout.getUsername())) {

            sysUser.setEmail(accout.getUsername());

        } else if (Regex.isMobile(accout.getUsername())) {

            sysUser.setMobile(accout.getUsername());

        } else {

            sysUser.setUsername(accout.getUsername());

        }

        //根据用户的账户名获取用户信息
        sysUser = sysUserService.findUserByUsername(sysUser);

        if (sysUser != null) {
            if (sysUser.getPassword().equals(
                    QEncodeUtil.md5Encrypt(accout.getPassword()))) {
                //判断登录源
                if (loginType == Constants.MODULE_TYPE_APP) {
                    //APP移动端登录

                    QuerySysUserTokenCondition condition = new QuerySysUserTokenCondition();
                    condition.setUserid(sysUser.getUserid());
                    SysUserToken userToken = sysUserTokenService.findUserTokenByCondition(condition);
                    //如果用户令牌不存在
                    if (userToken == null) {
                        //创建用户的令牌
                        userToken = new SysUserToken();
                        TokenGernerator.setupUserToken(userToken,sysUser.getUserid());
                        sysUserTokenService.insertSelective(userToken);

                        //增加token到缓存中
                        TokenCacheTimer.addUserToken(userToken.getToken(),userToken);
                    } else if (userToken.getOuttime().getTime() < new Date().getTime()) {
                        //清除缓存中的token
                        TokenCacheTimer.clearToken(userToken.getToken());

                        TokenGernerator.setupUserToken(userToken,sysUser.getUserid());
                        sysUserTokenService.updateByPrimaryKeySelective(userToken);

                        //增加token到缓存中
                        TokenCacheTimer.addUserToken(userToken.getToken(),userToken);
                    }
                    //设置为登录状态
                    super.savePrincipalLoginState(loginType, sysUser,userToken.getToken());
                    return WebResult.success().put("token", userToken.getToken()).put("data",sysUser.getNtype()).put("username",sysUser.getUsername()).toMap();
                } else {
                    //PC端或微信登录
                    super.savePrincipalLoginState(loginType, sysUser);
                    if (StringUtils.isNotBlank(accout.getOpenId())) {
                        QuerySysUserCondition conditon = new QuerySysUserCondition();
                        conditon.setOpenid(accout.getOpenId());
                        SysUserDto loginUser = sysUserService.findByCondition(conditon);
                        if (loginUser == null && StringUtils.isBlank(sysUser.getOpenid()) && StringUtils.isNotBlank(accout.getOpenId())) {
                            sysUser.setOpenid(accout.getOpenId());
                            sysUserService.updateByPrimaryKey(sysUser);
                        }
                    }
                    return WebResult.success().put("type",sysUser.getNtype()).toMap();
                }

            }

            return WebResult.failure("密码错误，请重新输入").toMap();

        }

        return WebResult.failure("账号不存在,请输入正确的用户名/手机号").toMap();

    }



    /**
     * @return 登出结果
     * @Title: userQuit()
     * @Description: TODO(系统用户登出)
     * @author Jerry
     * @date 2016-10-17 03:30:20
     */
    protected Map<String, Object> userQuit() throws Exception {

        SessionManager.destroySession();

        return WebResult.success().info("操作成功").toMap();
    }

}
